package com.example.project.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.project.annotation.AuthCheck;
import com.example.project.common.*;
import com.example.project.constant.CommonConstant;
import com.example.project.constant.UserConstant;
import com.example.project.exception.BusinessException;
import com.example.project.model.enums.InterfaceInfoStatusEnum;
import com.example.project.service.InterfaceInfoService;

import com.example.apiclientsdk.client.ApiClient;

import com.example.apicommon.model.entity.InterfaceInfo;
import com.example.apicommon.model.entity.User;

import com.example.project.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.example.project.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.example.project.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.example.project.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.example.project.service.UserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;



/**
 * 接口管理
 *
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private ApiClient apiClient; // SDK

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 发布
     * 前端管理员，点击发布 ，发送 接口的 id （即 InterfaceInfoID）
     * 可以选择删掉能够调用
     * 1. 数据库表 `InterfaceInfo` 查询 此接口是否存在
     * 2. 接口存在， 尝试根据 它在数据库中的 url，动态得调用 第三方的接口，看看是不是真的能用
     * 3. 能用， 修改 Status = InterfaceInfoStatusEnum.ONLINE
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        // 1. 判断是否存在, 使用的返回值类型是 api-common ; 实际做查询还是backend里的 Service
        com.example.apicommon.model.entity.InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 登录用户的 accessKey  secretKey
        User loginUser = userService.getLoginUser(request);
        // SDK 传入 ak sk, 当前登录用户的client
        ApiClient loginClient = new ApiClient(loginUser.getAccessKey(), loginUser.getSecretKey());

        Method method = null; // 需要被测试调用的方法
        String interfaceInfoName = oldInterfaceInfo.getName() + "Test"; // 方法的名字 + Test
        String requestParams = JSONUtil.formatJsonStr(oldInterfaceInfo.getRequestParams()); // 方法的参数 [{"name":"username","type":"string"}] 字符串
        JSONArray requestParamsArray = JSONUtil.parseArray(requestParams); // [{"name":"username","type":"string"}] Json格式数组
        List<Class> paramClassList = new ArrayList<>(); // 方法interfaceInfoName()的参数列表的具体类型的Class对象

        requestParamsArray.forEach(param -> {
            JSONObject jsonParam = (JSONObject) param;
            String classpath =  ClassUtils.getPath(jsonParam.get("type", String.class));
            try {
                paramClassList.add(Class.forName(classpath));
            } catch (ClassNotFoundException e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败, 获取参数列表反射类异常");
            }
        });

//        for (Object obj : requestParamsArray) {
//            JSONObject param = (JSONObject) obj; // {"name":"username","type":"string"} JSONObject对象【实质是 Map】
//            String classpath = param.get("type", String.class); // classpath = "string" 当前参数的类全路径！！！
//            try {
//                Class<?> paramClass = Class.forName(classpath); // paramClass = String.class 当前参数的 Class 对象
//                paramClassList.add(paramClass);
//            } catch (ClassNotFoundException e) {
//                throw new RuntimeException(e);
//            }
//        }

        Class[] paramClassArray = paramClassList.toArray(new Class[0]);
        if (paramClassArray.length == 0) {
            paramClassArray = null;
        }
        try {
            method = ApiClient.class.getDeclaredMethod(interfaceInfoName, paramClassArray);
        } catch (NoSuchMethodException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败, 接口不存在");
        }

        Object invokeResult = null; // invokeResult 规定是 true / false
        boolean invokeSuccess = false;
        Object[] paramObjArray = null;
        if (paramClassArray != null) {
            paramObjArray = new Object[paramClassArray.length];
        }
        try {
            method.setAccessible(true); // online方法实际调用的测试接口 是 接口名字+Test 组成的 私有方法在SDK中，由这个提前写好的私有方法来调用真正对应的 接口
            invokeResult = method.invoke(loginClient, paramObjArray);
            invokeSuccess = (boolean) invokeResult;
        } catch (IllegalAccessException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败, 接口测试调用失败, IllegalAccessException");
        } catch (InvocationTargetException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败, 接口测试调用失败, InvocationTargetException");
        }

        if (!invokeSuccess) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败, invokeSuccess is false");
        }

/*
        // 调用SDK里的方法，带上aK、sK等，发请求到网关 8090 ，网关转发到 8123 调用接口 getUsernameByPost
        // 此接口根据User返回username 如果返回成功，说明接口可以调用
        String username = apiClient.getUsernameByPost(user);
        if (StringUtils.isBlank(username)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败");
        }
*/
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 下线
     * 1. 数据库表 `InterfaceInfo` 查询 此接口是否存在
     * 2.修改 Status = InterfaceInfoStatusEnum.OFFLINE
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                      HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 测试调用
     * 1. 数据库表 `InterfaceInfo` 查询 此接口是否存在
     * 2. 数据库表 `InterfaceInfo` 查询 此接口是否 ONLINE
     * 3. 拿到当前登录的用户 User loginUser = userService.getLoginUser(request);
     * 4. 当前用户的 accessKey  secretKey 传入 SDK.ApiClient 得到 tempClient
     * 5. 调用 SDK 里的 需要被测试的接口方法 ， 判断调用是否成功，这就意味着其实所有的接口都不能是 void 返回值，
     * 6. controller层 也的确 需要返回东西  void方法没有意义 因为这是要提供给客户的 肯定要有什么东西来返回一下
     * @param interfaceInfoInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = interfaceInfoInvokeRequest.getId();
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        // 判断是否存在
        com.example.apicommon.model.entity.InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已关闭");
        }
        // 登录用户的 accessKey  secretKey
        User loginUser = userService.getLoginUser(request);
        // SDK 传入 ak sk, 当前登录用户的client
        ApiClient loginClient = new ApiClient(loginUser.getAccessKey(), loginUser.getSecretKey());

        com.example.apiclientsdk.model.User user = GsonUtils.getObjFromJson(userRequestParams, com.example.apiclientsdk.model.User.class);

        String usernameByPost = loginClient.getUsernameByPost(user);
        return ResultUtils.success(usernameByPost);
    }

}
